<?php
declare (strict_types = 1);

namespace app\api\service;

use think\Exception;
use think\facade\Cache;
use think\facade\Request;

class UserToken
{
    /**
     * 生成用户访问凭证
     */
    public static function generateAccessToken(array $memberInfo)
    {
        $hash = config('token.hash_method');
        $uid = $memberInfo['uid'];
        $session_key = $memberInfo['session_key'];
        $token = call_user_func($hash, $uid . $session_key . time() . config('token.appKey'));
        Cache::set( $token,  $memberInfo, config('token.expire_time') );
        return $token;
    }

    /**
     * 验证token
     */
    public static function checkAccessToken($token)
    {
        return Cache::has($token) ? Cache::get($token) : false;
    }

    /**
     * 检查有没有访问token
     */
    public static function checkAccessMustHasToken()
    {
        $userToken = Request::header('token');

        if( empty($userToken) ){
            throw new Exception('缺失token参数,请正常登录');
        }

        if(Cache::has($userToken) === false){
            throw new Exception();
        }

        // 更新user_token 的过期时间 (延期，保证其有效期内连续操作不掉线)
        $info = Cache::get($userToken);
        Cache::set($userToken,$info,config('api.token_expire_time'));

        return $info;
    }

    /**
     * 销毁访问凭证
     */
    public static function clearAccessToken()
    {
        $token = Request::header('token');
        if(empty($token) || Cache::has($token) === false){
            return false;
        }
        return Cache::delete($token);
    }

    /**
     * 检测会员是否登录系统
     */
    public static function isLogin()
    {
        $token = Request::header('token');
        if(empty($token) || Cache::has($token) === false){
            return false;
        }
        return self::getCurrentUid();
    }

    /**
     * 获取当前访问的用户id
     */
    public static function getCurrentUid()
    {
        $uid = self::getCurrentTokenInfo('id');
        return $uid;
    }

    /**
     * 获取token里的信息
     */
    public static function getCurrentTokenInfo($key='')
    {
        $vars = self::checkAccessMustHasToken();

        if( empty($key) ){
            return $vars;
        }

        if(!array_key_exists($key, $vars)){
            throw new \think\Exception('尝试获取的Token变量并不存在');
        }

        return $vars[$key];
    }
}